package ar.uba.fi.tonyvaliente.web.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ar.uba.fi.tonyvaliente.documents.DocumentManager;
import ar.uba.fi.tonyvaliente.documents.QueryDocumentsResult;
import ar.uba.fi.tonyvaliente.web.manager.DocumentSearchManager;
import ar.uba.fi.tonyvaliente.web.search.DocumentSearchResult;
import ar.uba.fi.tonyvaliente.web.search.Query;

/**
 * Servlet implementation class for Servlet: DocumentSearch
 *
 */
 public class DocumentSearch extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
   static final long serialVersionUID = 1L;
   
	public DocumentSearch() {
		super();
	}   	
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}  	
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	private void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

	       String submit = request.getParameter("submit");
	       String query = request.getParameter("query");
	       String indexType = request.getParameter("indexType");
	       
	       System.out.println("submit " + submit);
	       System.out.println("query " + query);
	       
	       String forward = "searchDocuments.jsp";
	       
	       if(submit != null){
	    	   
	    		   
		    	   DocumentSearchManager searchManager = new DocumentSearchManager(indexType);
		    	   if(submit.equalsIgnoreCase("Get Documents")){
		    		   if(indexType != null){
				    	   Query queryObject = new Query();
				    	   queryObject.setValue(query);
				    	   
				    	   List<DocumentSearchResult> documents = searchManager.queryIndex(query);
				    	   
				    	   queryObject.setDocuments(documents);
				    	   request.setAttribute("query", queryObject);
		    		   }else{
		    			   request.setAttribute("message", "The index Type is mandatory");
		    		   }
		    	   }else if(submit.equalsIgnoreCase("show")){
		    		   
		    		   String docID = request.getParameter("docID");
		    		   
		    		   String contenido = searchManager.getDocument(Integer.parseInt(docID));
		    		   request.setAttribute("content", contenido);
		    		   request.setAttribute("message", null);
		    		   forward = "viewDocument.jsp";
		    		   
		    	   }
	       }
           RequestDispatcher dispatcher = request.getRequestDispatcher(forward);
           dispatcher.forward(request, response);

	}   	  	    
}